package com.sgb.kjwl.utils;

import android.content.Context;
import android.os.Environment;

import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.download.DownloadListner;
import com.swgk.core.download.DownloadManager;
import com.swgk.core.mmkvutil.MkvUtils;

import java.io.File;

/**
 * @Author : 作者  Gw
 * @Time : 2021/1/9 13:32
 * @Page: com.sgb.kjwl.utils
 * @Description :广告专用下载
 */
public class DownLoadAdvUtil {
    public static void getFileFromServer(Context context, String uri) throws Exception {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            downloadFile(context,uri);
        }
    }

    /**
     * 广告图下载
     * @param context
     * @param uri
     */
    public static void downloadFile(Context context,String uri){
        File filePath = context.getExternalFilesDir("adv" + File.separator + "download");
        String fileName;
        if (uri.contains("gif")){
            fileName = "adv_" + System.currentTimeMillis()+".gif";
        }else {
            fileName = "adv_" + System.currentTimeMillis();
        }

        //创建下载任务管理器
        DownloadManager mDownloadManager = DownloadManager.getInstance();
        //将下载任务添加至任务管理器中，并创建下载线程
        mDownloadManager.add(uri, filePath.getPath(), fileName, new DownloadListner() {
            @Override
            public void onFinished() {
                MkvUtils.get().putString(MkvUtils.CommomData, CacheMarker.AdvUrlTag, uri);
                MkvUtils.get().putString(MkvUtils.CommomData, CacheMarker.AdvFilePathTag,new File(filePath, fileName).getPath());
            }

            @Override
            public void onProgress(float progress, boolean isDownloading) {
            }

            @Override
            public void onPause() {
            }

            @Override
            public void onCancel() {
            }
        });
        mDownloadManager.download(uri); //继续下载
    }
}
